import { ref } from 'vue'

/**
 * Loading状态管理钩子
 * @returns {Object}
 */
export function useLoading() {
  const loading = ref(false)
  
  /**
   * 执行异步操作并自动管理loading状态
   * @param {Function} fn - 异步函数
   * @param {Object} options - 配置项
   * @returns {Promise}
   */
  const runWithLoading = async (fn, options = {}) => {
    const { showToast = true, errorMsg = '操作失败' } = options
    
    try {
      loading.value = true
      return await fn()
    } catch (error) {
      console.error(error)
      if (showToast) {
        uni.showToast({
          title: error.message || errorMsg,
          icon: 'none'
        })
      }
      return Promise.reject(error)
    } finally {
      loading.value = false
    }
  }
  
  return {
    loading,
    runWithLoading
  }
} 